<template>
<div class="wrapper">
  <q-field :error="error" :error-label="errorMsg">
    <q-input v-model="tokenInput"
             type="password"
             float-label="请输入令牌："
             :readonly="loginBtnDisable"
             ></q-input>
  </q-field>
  <q-btn label="登入"
         color="primary"
         @click="enterToken"
         key="enterToken"
         :disable="loginBtnDisable"></q-btn>
  <q-btn label="登出"
         color="black"
         @click="delToken"
         key="delToken"
         :disable="!loginBtnDisable"></q-btn>
</div>
</template>

<script>
import {
  mapState,
  mapMutations,
  mapActions } from 'vuex'

export default {
  computed: {
    error () {
      return !this.isValid()
    },
    loginBtnDisable () {
      return this.isValid()
    }
  },
  data () {
    return {
      // error: false,
      errorMsg: '令牌无效',
      // loginBtnDisable: false
      tokenInput: ''
    }
  },
  mounted: function () {
    this.tokenInput = this.$store.state.subtoken.token
  },
  methods: {
    ...mapState('subtoken', [
      'isValid'
    ]),
    ...mapActions('subtoken', [
      'getSubtoken'
    ]),
    ...mapMutations('subtoken', [
      'remember',
      'forget',
      'setValid'
    ]),
    enterToken () {
      // TODO: check length
      this.remember(this.tokenInput)
      this.getSubtoken()
    },
    delToken () {
      this.forget()
      this.setValid(false)
      // // jump back root
      this.$nextTick(function () {
        this.$router.push('/')
      })
    }
  }
}
</script>
<style>

</style>
